<?php

namespace app\admin\controller\user;

use app\admin\library\ImSig;
use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('visitingmaterials')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->getRelation('visitingmaterials')->visible(['name','gender','birthday','id_card','return_permit','hk_address','hk_address','nd_address','hk_mobile','nd_mobile','email','fm_mobile','native_place','education','cognitive_approach','is_voter','trade_union']);
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);

                $region_address = db('region')->where(['id'=>$v->province])->value('name');
                $city = db('region')->where(['id'=>$v->city])->value('name');
                if ( $city ) {
                    $region_address = $region_address.$city;
                    $district = db('region')->where(['id'=>$v->district])->value('name');
                    if ( $district ) {
                        $region_address = $region_address.$district;
                    }
                }
                $v->region_address = $region_address?$region_address:'';

            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig("updateuser", $this->auth->check("user/user/updateuser"));
        $this->assignconfig("updatedit", $this->auth->check("user/user/edit"));
        $this->assignconfig("dengji", $this->auth->check("registr_activity_user/user_list"));
        $this->assignconfig("liuyan", $this->auth->check("user/user/edit"));
        $this->assignconfig("qiandao", $this->auth->check("user/user/edit"));
        $this->assignconfig("wenjuan", $this->auth->check("user/user/edit"));
        return $this->view->fetch();
    }

    /**
     * 分配用戶
     */
    public function indexs($ids = null,$staff_id = 0)
    {
        $arr = explode(',', $ids);
        if ( !$arr[0] ) {
            $arr = [];
        }
        $arrs = [];
        foreach ($arr as $key => $value) {
            $arrs[] = (int)$value;
        }
        $this->assignconfig("arr", $arrs);
        $this->assignconfig("staff_id", $staff_id);
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_buf = ['user.staff_id'=>0];
            if ( $staff_id >0  ) {
                $where_buf = ['user.staff_id'=>['in',[0,$staff_id]]];
            }
            $list = $this->model
                ->with('group')
                ->where($where)
                ->where($where_buf)
                ->where(['v.id'=>null])
                ->join('volunteer v','v.user_id = user.id','LEFT')
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);

                $region_address = db('region')->where(['id'=>$v->province])->value('name');
                $city = db('region')->where(['id'=>$v->city])->value('name');
                if ( $city ) {
                    $region_address = $region_address.$city;
                    $district = db('region')->where(['id'=>$v->district])->value('name');
                    if ( $district ) {
                        $region_address = $region_address.$district;
                    }
                }
                $v->region_address = $region_address?$region_address:'';

            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 關懷圈選擇用戶
     */
    public function caring_task_user($ids = 0)
    {
        $this->assignconfig("ids", $ids);
        $this->assignconfig("arr", [(int)$ids]);
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->where(['v.id'=>null])
                ->join('volunteer v','v.user_id = user.id','LEFT')
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);

                $region_address = db('region')->where(['id'=>$v->province])->value('name');
                $city = db('region')->where(['id'=>$v->city])->value('name');
                if ( $city ) {
                    $region_address = $region_address.$city;
                    $district = db('region')->where(['id'=>$v->district])->value('name');
                    if ( $district ) {
                        $region_address = $region_address.$district;
                    }
                }
                $v->region_address = $region_address?$region_address:'';

            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }



    /**
     * 查看
     */
    public function staff_users($ids = null)
    {
        $this->assignconfig("ids", $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_buf = ['staff_id'=>$ids];
            $list = $this->model
                ->with('group')
                ->where($where)
                ->where($where_buf)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);

                $region_address = db('region')->where(['id'=>$v->province])->value('name');
                $city = db('region')->where(['id'=>$v->city])->value('name');
                if ( $city ) {
                    $region_address = $region_address.$city;
                    $district = db('region')->where(['id'=>$v->district])->value('name');
                    if ( $district ) {
                        $region_address = $region_address.$district;
                    }
                }
                $v->region_address = $region_address?$region_address:'';

            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $models = new \app\admin\model\VisitingMaterials;
        $this->view->assign("isVoterList", $models->getIsVoterList());
        $this->view->assign("genderList", $models->getGenderList());
        $this->view->assign("isEducationList", $models->getEducationList());
        $this->view->assign("isCognitiveApproachList", $models->getCognitiveApproachList());

        if ($this->request->isPost()) {
            $this->token();
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $paramss = $this->request->post("rows/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $count = db('user')->where(['mobile'=>$params['mobile']])->count();
                if ( $count ) {
                    $this->error('用戶賬號重復');
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                    $params['province'] = input('province',0);
                    $params['city'] = input('city',0);
                    $params['district'] = input('district',0);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {


                    $row = $models->get(['user_id'=>$this->model->id]);

                    if ($paramss) {
                        if ( !$paramss['is_voter'] ) {
                            unset($paramss['is_voter']);
                        }
                        if ( !$paramss['gender'] ) {
                            unset($paramss['gender']);
                        }
                        if ( !$paramss['birthday'] ) {
                            unset($paramss['birthday']);
                        }
                        if ( $row ) {
                            $result = $row->allowField(true)->save($paramss);
                        }else{
                            $paramss['user_id'] = $this->model->id;
                            $result = $models->save($paramss);
                        }

                    }



                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $province = db('region')->field('id as value, name')->where(['id'=>$row['province']])->find();
        $city = db('region')->field('id as value, name')->where(['id'=>$row['city']])->find();
        $district = db('region')->field('id as value, name')->where(['id'=>$row['district']])->find();
        $this->view->assign("province", $province);
        $this->view->assign("city", $city);
        $this->view->assign("district", $district);

        $models = new \app\admin\model\VisitingMaterials;
        $this->view->assign("isVoterList", $models->getIsVoterList());
        $this->view->assign("genderList", $models->getGenderList());
        $this->view->assign("isEducationList", $models->getEducationList());
        $this->view->assign("isCognitiveApproachList", $models->getCognitiveApproachList());

        $rows = $models->get(['user_id'=>$row->id]);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $paramss = $this->request->post("rows/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                $count = db('user')->where(['mobile'=>$params['mobile'],'id'=>['neq',$row->id]])->count();
                if ( $count ) {
                    $this->error('用戶賬號重復');
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                    $params['province'] = input('province',0);
                    $params['city'] = input('city',0);
                    $params['district'] = input('district',0);
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if ($paramss) {
                        if ( !$paramss['is_voter'] ) {
                            unset($paramss['is_voter']);
                        }
                        if ( !$paramss['gender'] ) {
                            unset($paramss['gender']);
                        }
                        if ( !$paramss['birthday'] ) {
                            unset($paramss['birthday']);
                        }
                        if ( $rows ) {
                            $result = $rows->allowField(true)->save($paramss);
                        }else{
                            $paramss['user_id'] = $row->id;
                            $result = $models->save($paramss);
                        }

                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("rows", $rows);
        return $this->view->fetch();
    }

    // /**
    //  * 编辑
    //  */
    // public function edit($ids = null)
    // {
    //     if ($this->request->isPost()) {
    //         $this->token();
    //     }
    //     $row = $this->model->get($ids);
    //     $this->modelValidate = true;
    //     if (!$row) {
    //         $this->error(__('No Results were found'));
    //     }
    //     $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
    //     return parent::edit($ids);
    // }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }
    /**
     * 启用合作
     */
    public function updateuser($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $title = '';
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['status'] == 'hidden') {
                        $where = ['status'=>'normal'];
                    }else{
                        $where = ['status'=>'hidden'];;
                    }
                    $count += $v->save($where);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('操作失败'));
            }
        }
        $this->error(__('操作失败', 'ids'));
    }



    public function chat()
    {
        $this->redirect('/dist/index.html');
        return 1;
    }


    /**
     * Im客服登入
     */
    public function im_login()
    {
        $user = 'kefu';
        $im   = new ImSig();
        $res = $im->account_check($user,false);
        if(!isset($res[$user])) throw new \Exception('客服账号不存，请联系管理员');
        if($res[$user]['ResultCode'] == 0 &&  $res[$user]['AccountStatus'] == 'NotImported'){
            //创建客服账号
            $data = [
                'Identifier'=>$user,
                'Nick'=>'客服'
            ];
            $res = $im->account_import($data,false);
            if(!isset($res['ActionStatus']) || $res['ActionStatus'] !== "OK" || !isset($res['ErrorCode']) || $res['ErrorCode'] != 0)
                throw new \Exception('生成客服账号失败');
            sleep(2);
        }elseif ($res[$user]['ResultCode'] == 0 &&  $res[$user]['AccountStatus'] == 'Imported'){

        }else{
            throw new \Exception('客服账号不存，请联系管理员');
        }

        $sig  = $im->genSig($user,0,false);
        return json(['userID'=>$user,'userSig'=>$sig]);
    }


}
